import React from 'react'
import {connect} from 'react-redux'
import BasicInfo from 'components/basic-info';
import {messages} from 'share/common';
import debounce from 'lodash.debounce';
import menuRoute from 'routes/menuRoute'
import { Button, Input, message, Spin, Affix, Modal, Checkbox } from 'antd';
import ResizeTable from 'components/resize-table'
import ListSelector from 'components/list-selector';
import 'styles/setting/wait-for-billing/invoice-status-query.scss';
import interfaceService from "containers/financial-account/interface-definition/interface-service";
const Search = Input.Search;

class sceneDetail extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      infoList: [
        {type: 'input', id: 'sceneCode', label: messages('financial-account.key43')/*场景编码*/},
        {type: 'input', id: 'sceneName', label: messages('financial-account.key44')/*场景名称*/},
        {type: 'input', id: 'comment', label: messages('financial-account.key45')/*场景说明*/},
        {type: 'switch', id: 'isDefault', label: messages('financial-account.key5')/*是否预置*/, render: (value) => value ? messages('common.yes')/*是*/ : messages('common.no')/*否*/},
        {type: 'switch', id: 'isEnable', label: messages('common.column.status')/*状态*/, render: (value) => value ? messages('common.valid')/*生效*/ : messages('financial-account.key6')/*不生效*/},
      ],
      infoData: {},
      columns: [
        {title: messages('financial-account.key119')/*核算业务编码*/, dataIndex: 'typeCode', width: '28%'},
        {title: messages('financial-account.key120')/*核算业务名称*/, dataIndex: 'typeName', width: '28%'},
        {title: messages('financial-account.key156')/*关联来源数据*/, dataIndex: 'relative', render: (value, record) => <a onClick={() => {this.handleRelative(record)}}>{messages('financial-account.key156')/*关联来源数据*/}</a>},
        {title: messages('financial-account.key5')/*是否预置*/, width: 96, dataIndex: 'isDefault', render: (value) => value ? messages('components.key378')/*是*/ : messages('components.key377')/*否*/},
        {title: messages('common.column.status')/*状态*/, width: 80, dataIndex: 'isEnable', render: (value) => value ? messages('common.valid')/*生效*/ : messages('financial-account.key6')/*不生效*/},
        {title: messages('common.operation')/*操作*/, width: 72, dataIndex: 'operation', render: (value,record) => {
            return <span>
              {record.isDefault ? '-' : <a onClick={() => this.handleDelete(record)}>{messages('common.delete')/*删除*/}</a>}
            </span>;}}
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      relativePagination: {
        total: 0,
        defaultPageSize: 5
      },
      page: 0,
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      selectedDataIds: [],
      showSlideFrame: false,
      searchKey: '',
      addLoading: false,
      deleteLoading: false,
      relativeShow: false,
      relativeLoading: false,
      relativeData: [],
      relativePage: 0,
      relativeColumns: [
        {title: messages('financial-account.key63')/*来源数据编码*/, dataIndex: 'detailSourceCode'},
        {title: messages('financial-account.key64')/*来源数据名称*/, dataIndex: 'detailSourceName'},
        {title: messages('financial-account.key3')/*说明*/, dataIndex: 'comment'},
        {title: messages('financial-account.key157')/*引用单元*/, dataIndex: 'isRelatedUnit', render: (value,record) => <Checkbox checked={value} onChange={choose => this.handleCheck(choose, record, 'isRelatedUnit')}/>},
        {title: messages('financial-account.key158')/*循环单元*/, dataIndex: 'isCirUnit', render: (value,record) => <Checkbox checked={value} onChange={choose => this.handleCheck(choose, record, 'isCirUnit')}/>}
      ],
      checkChangeRecord: []
    };
    this.getList = debounce(this.getList,500);
  }

  componentDidMount() {
    this.setState({infoData: this.props.sceneDefinition},() => {
      this.getList();
    });
  }

  onSelectChange = (selectedRowKeys) => {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    let { selectedDataIds } = this.state;
    if(!selected){
      changeRows.map(record => {
        selectedDataIds.map((select, index) => {
          if( select.id === record.id ){
            selectedDataIds.splice(index, 1);
          }
        })
      });
    } else {
      selectedRows.map(item => {
        let isContainer = false;
        selectedDataIds.map(select => {
          if( select.id === item.id ){
            isContainer = true;
          }
        });
        !isContainer && (selectedDataIds.push(item));
      });
    }
    this.setState({selectedDataIds});
  };

  onSelectItem = (record, selected) => {
    let {selectedDataIds, rowSelection} = this.state;
    if(!selected){
      selectedDataIds.map((select, index) => {
        if( select.id === record.id ){
          selectedDataIds.splice(index, 1);
        }
      })
    } else {
      selectedDataIds.push(record);
    }
    this.setState({ selectedDataIds ,rowSelection: rowSelection });
  };

  getList = () => {
    const { searchKey, page, infoData } = this.state;
    let temp = {
      functionDefCodeOrName: searchKey,
      sceneDefId: infoData.id
    };
    Object.keys(temp).map(item => {
      !temp[item] && delete temp[item];
    });
    temp.page = page;
    this.setState({loading: true});
    interfaceService.getBusinessList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  onRelativeChangePager = (page, record) => {
    if (page - 1 !== this.state.relativePage)
      this.setState({
        relativePage: page - 1
      }, () => {
        this.handleRelative(record);
      })
  };

  handleChangeKey = (e) => {
    this.setState({searchKey: e.target.value, page: 0},() => {
      this.getList();
    })
  };

  handleAdd = () => {
    this.setState({showSlideFrame: true});
  };

  handleRelative = record => {
    const { sceneDefinition } = this.props;
    const { relativePage, checkChangeRecord } = this.state;
    this.setState({relativeShow: true, relativeLoading: true},() => {
      interfaceService.getRelativeList({functionDefineId: record.id, sceneDefineId: sceneDefinition.id, page: relativePage, size: 5}).then(res => {
        res.data.rows.map((item, index) => {
          checkChangeRecord.map(it => {
            if(this.judgeEqual(it,item)){
              item.isRelatedUnit = it.isRelatedUnit;
              item.isCirUnit = it.isCirUnit;
            }
          });
          item.index = index + relativePage * 5;
        });
        this.setState({
          relativeLoading: false,
          relativeData: res.data.rows,
          relativePagination: {
            total: Number(res.data.total),
            current: relativePage + 1,
            onChange: page => this.onRelativeChangePager(page, record),
          }
        });
      }).catch(e => {
        this.setState({relativeLoading: false});
        message.error(e.response.data.message);
      })
    });
  };

  handleCheck = (value, record, type) => {
    const { relativeData, checkChangeRecord } = this.state;
    relativeData.map(item => {
      if(this.judgeEqual(item, record)){
        item[type] = value.target.checked;
        checkChangeRecord.map((pair, index) => {
          if(this.judgeEqual(pair, item)){
            checkChangeRecord.splice(index, 1, item);
          }
        });
        checkChangeRecord.filter(pair => this.judgeEqual(pair, item)).length === 0 && checkChangeRecord.push(item);
      }
    });
    this.setState({relativeData, checkChangeRecord});
  };

  judgeEqual = (record, item) => {
    if(record.sceneFunctionDefineId === item.sceneFunctionDefineId && record.functionSourceGroupId === item.functionSourceGroupId){
      return true;
    } else {
      return false;
    }
  };

  handleDelete = (record) => {
    const { selectedDataIds, rowSelection } = this.state;
    let ids = [];
    let shouldDelete = true;
    if (record) {
      ids.push(record.sceneDefAndFunctionDefRefId);
    } else {
      selectedDataIds.every(item => {
        if(item.isDefault){
          shouldDelete = false;
          message.error(messages('financial-account.key161')/*预置的无法删除*/);
          return false;
        }
        ids.push(item.sceneDefAndFunctionDefRefId);
        return true;
      });
    }
    if(shouldDelete){
      if(ids.length === 0){
        message.error(messages('financial-account.key148')/*请选择再进行删除*/);
        return -1;
      }
      this.setState({deleteLoading: true});
      interfaceService.deleteSceneDetail(ids).then((res) => {
        this.setState({deleteLoading: false},() => {
          if(res.data){
            message.success(messages('common.operate.success')/*操作成功*/);
            this.getList();
          } else {
            message.error(messages('common.operate.filed')/*操作失败*/);
          }
        });
      }).catch(e => {
        this.setState({deleteLoading: false});
        message.error(e.response.data.message);
      })
    } else {
      rowSelection.selectedRowKeys = [];
      this.setState({selectedDataIds: [], rowSelection})
    }
  };

  handleSelectAddition = (value) => {
    const { sceneDefinition, user } = this.props;
    if(value && value.result.length){
      let temp = [];
      value.result.map(item => {
        temp.push({
          sceneDefineId: sceneDefinition.id,
          functionDefineId: item.id,
          isEnable: true,
          isDefault: false
        });
      });
      this.setState({addLoading: true});
      interfaceService.addSceneDetail(temp,user.userOID).then(() => {
        this.setState({ showSlideFrame: false, addLoading: false},() => {
          this.getList();
        });
      }).catch(e => {
        message.error(e.response.data.message);
        this.setState({
          addLoading: false,
          showSlideFrame: false
        });
      });
    } else {
      this.setState({showSlideFrame: false});
    }
  };

  goBack = () => {
    this.context.router.push(menuRoute.getRouteItem('interface-definition-detail').url.replace(':tab','accounting-background-definition'));
  };

  relativeOk = () => {
    const { checkChangeRecord } = this.state;
    const { user } = this.props;
    if(checkChangeRecord.length === 0){
      this.setState({relativeShow: false});
    } else {
      let params = [];
      checkChangeRecord.map(item => {
        let tempObj = {
          sceneFunctionDefineId: item.sceneFunctionDefineId,
          functionSourceGroupId: item.functionSourceGroupId,
          isRelatedUnit: item.isRelatedUnit ? true : false,
          isCirUnit: item.isCirUnit ? true : false
        };
        item.id && (tempObj.id = item.id);
        params.push(tempObj);
      });
      interfaceService.saveRelativeList(params, user.userOID).then(() => {
        this.setState({relativeShow: false, checkChangeRecord: [], relativePage: 0});
      }).catch(e => {
        message.error(e.response.data.message);
      })
    }
  };

  render(){
    const { infoList, infoData, columns, data, loading, pagination, rowSelection, showSlideFrame, addLoading,
      deleteLoading, relativeShow, relativeData, relativeLoading, relativeColumns, relativePagination, selectedDataIds } = this.state;
    const { sceneDefinition } = this.props;
    return(
      <Spin spinning={addLoading}>
        <div className="invoice-status">
          <BasicInfo infoList={infoList}
                     infoData={infoData}
                     isHideEditBtn={true}/>
          <div style={{margin: '10px 0px'}}>
            <Button type="primary" onClick={this.handleAdd}>{messages('common.create')}</Button>
            <Button onClick={() => this.handleDelete()} style={{marginLeft: '10px'}} disabled={selectedDataIds.length === 0}
                    loading={deleteLoading}>{messages('common.delete')/*删除*/}</Button>
            <Search onChange={e => this.handleChangeKey(e)}
                    style={{display: 'block', float: 'right', width: '400px', top: '50%'}}
                    placeholder={messages('financial-account.key72')/*请输入编码/名称*/}/>
          </div>
          <ResizeTable
            columns={columns}
            dataSource={data}
            loading={loading}
            rowKey={'id'}
            rowSelection={rowSelection}
            pagination={pagination}
            bordered/>
          <ListSelector visible={showSlideFrame}
                        selectedData={null}
                        type="finance_account"
                        extraParams={{
                          setOfBooksId: sceneDefinition.setOfBooksId,
                          sceneDefineId: sceneDefinition.id
                        }}
                        onOk={this.handleSelectAddition}
                        onCancel={() => this.setState({showSlideFrame: false})}/>
          <Modal visible={relativeShow}
                 onOk={this.relativeOk}
                 width={900}
                 onCancel={() => {this.setState({relativeShow: false, checkChangeRecord: [], relativePage: 0})}}
                 title={messages('financial-account.key156')/*关联来源数据*/}>
            <ResizeTable
              loading={relativeLoading}
              dataSource={relativeData}
              pagination={relativePagination}
              columns={relativeColumns}
              rowKey={'index'}
              bordered/>
          </Modal>
          <Affix offsetBottom={0} className="bottom-bar">
            <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
          </Affix>
        </div>
      </Spin>
    )
  }
}

sceneDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    sceneDefinition: state.financialAccount.sceneDefinition,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(sceneDetail);
